// 获取应用实例
const app = getApp()

Page({
    data: {
        bom_index:0,
        is_show_choose_pro:false,
        buyer_list: [],
        supplier_list: [],
        supplier_total: 0,
        supplier_now_page: 0,
        supplier_keywords: '',
        limit: 50,
        sel_text: {
            buyer_text: '',
            type_text: '',
            supply_text: '',
        },
        formData: {
            purchase_time: '',
            purchase_name: '南昌岳歌',
            first_order: 1,
            buyer_id: 0,
            type: 2,
            supply_id: 0,
            sg_purchase_sn: '',
            year:''
        },
        bom_list: [],
        type_list: [
            {id: 1, name: '春'},
            {id: 2, name: '夏'},
            {id: 3, name: '秋'},
            {id: 4, name: '冬'},
            {id: 5, name: '通用'},
        ],
        is_shade_screen: false,
        is_show_choose_supplier: false,
        sel_table_head: [
            {name: '物料名称', field: 'material_name', is_checked: 1, width: 350},
            {name: '供应商', field: 'supply_name', is_checked: 0, width: 200},
            {name: '颜色', field: 'material_color', is_checked: 0, width: 120},
            {name: '采购数量', field: 'confirm_num', is_checked: 1, width: 200},
            {name: '预计交期', field: 'dead_line', is_checked: 1, width: 200},
            {name: '单位', field: 'unit', is_checked: 1, width: 150},
            {name: '单价', field: 'price', is_checked: 1, width: 150},
            {name: '用途', field: 'material_use', is_checked: 1, width: 200},
            {name: '成品简码', field: 'template_no', is_checked: 1, width: 200},
            {name: '成品图', field: 'template_images', is_checked: 1, width: 200},
            {name: '生产批次', field: 'total_bom_id', is_checked: 1, width: 200},
            {name: 'bom名称', field: 'bom_id', is_checked: 1, width: 200},
            {name: '单件用量', field: 'single_piece', is_checked: 1, width: 200},
            {name: '缩率', field: 'no_use_rate', is_checked: 1, width: 200},
            {name: '面料等级', field: 'material_grade', is_checked: 1, width: 200},
            {name: '等级分类', field: 'grade_category', is_checked: 1, width: 200},
            {name: '口袋布', field: 'pocketing', is_checked: 1, width: 200},
            {name: '外发工厂', field: 'outgoing_factory', is_checked: 1, width: 200},
            {name: '成品加工费', field: 'template_pro_cost', is_checked: 1, width: 200},
            {name: '成品零售价', field: 'template_retail_price', is_checked: 1, width: 200},
            {name: '下单件数', field: 'template_order_num', is_checked: 1, width: 200},
            {name: '物料图', field: 'temp_imgs', is_checked: 1, width: 200},
   
            {name: '备注', field: 'remark', is_checked: 1, width: 200},
        ],
        purchase_id: 0,
        edit_data: null,
        prop_list:[
          {"value":1,"label":"首单"},
          {"value":0,"label":"补单"},
          {"value":2,"label":"加单"},
          {"value":3,"label":"备料"}
        ],

        is_bl_options:[
          {"value":0,"label":"不是批量备料"},
          {"value":1,"label":"是批量备料"}
        ],
        sel_season_arr:[0,0],
        season_data:[
          {
              "label":"初春",
              "children":[
                {
                  "label":"初春1",
                },
                {
                  "label":"初春2",
                },
              ],
          },
          {
            "label":"正春",
            "children":[
              {
                "label":"正春1",
              },
              {
                "label":"正春2",
              },
            ],
          },
          {
            "label":"初夏",
            "children":[{
              "label":"初夏1",
              },
              {
                "label":"初夏2",
              },
            ],
          },
          {
            "label":"盛夏",
            "children":[
              {
                "label":"盛夏1",
              },
              {
                "label":"盛夏2",
              },
            ],
          },
          {
            "label":"初秋",
            "children":[
              {
                "label":"初秋1",
              },
              {
                "label":"初秋2",
              },
            ],
          },
          {
            "label":"深秋",
            "children":[
              {
                "label":"深秋1",
              },
              {
                "label":"深秋2",
              },
              
            ],
          },
          {
            "label":"初冬",
            "children":[
              {
                "label":"初冬1",
              },
              {
                "label":"初冬2",
              },
            ],
          },
          {
            "label":"深冬",
            "children":[
              {
                "label":"深冬1",
              },
              {
                "label":"深冬2",
              },
            ],
          },
          {
            "label":"通季",
            "children":[
              {
                "label":"通季",
              },
            ],
          }
      ],
      season_show:[
      ],
    },
    afterRead(event) {
      console.log('eventeventevent',event)
            let {index} = event.currentTarget.dataset
            var __this = this;
            const { file } = event.detail;
   
            const fileList = this.data.bom_list[index].fileList||[];
            file.forEach((v,k)=>{
              fileList.push({ ...v });
            })
            console.log(fileList)
            var setname = `bom_list[${index}].fileList`;
            this.setData({ [setname]:fileList });
    },
    deleteImage(e){
      let {index} = e.currentTarget.dataset
      let index2 = e.detail.index
      let bom_list = this.data.bom_list
      bom_list[index].fileList.splice(index2,1);
      this.setData({
        bom_list
      })
    },
       // 生产批次改变时
  proChange: function (e) {
    let bom_list = this.data.bom_list
    let {index} = e.currentTarget.dataset
    bom_list[index].total_bom_id = this.data.bom_list[index].pro_list[parseInt(e.detail.value)].total_bom_id;
    bom_list[index].totalbom_bom_list = this.data.bom_list[index].pro_list[parseInt(e.detail.value)].totalBomDetail;
    this.setData({
      bom_list,
    })
  },
  PreviewImg: function (events) {
    var pic_arr = events.currentTarget.dataset.pic;
    if (pic_arr.length == 0) {
        return false;
    }
    // 调用
    wx.previewImage({
        current: pic_arr[0],
        urls: pic_arr
    })
  },
    open_bom_select(e){
      this.setData({
        is_show_choose_pro:true,
        is_shade_screen:true,
        bom_index:e.currentTarget.dataset.index
      })
    },
    // 选择bom
    choose_bom: function (e) {
      // 验证是否选择的是否和之前一样
      let bom_list = this.data.bom_list;
      let bom_index = this.data.bom_index
      bom_list[bom_index].bom_id = {
        total_bom_detail_id:this.data.bom_list[bom_index].totalbom_bom_list[parseInt(e.currentTarget.dataset.index)].total_bom_detail_id,
        bom_option_name:this.data.bom_list[bom_index].totalbom_bom_list[parseInt(e.currentTarget.dataset.index)].bom_name
      }
      this.setData({
        bom_list
      });
      this.close_supplier_choose();
    },
    yearValueChange: function (e){
      var year = e.detail.value;
      this.setData({
        [`formData.year`]:year,
      })
    },
    // 风格分类值变化时
    seasonValueChange: function (e) {
      // console.log(e);
      var season_show = this.data.season_show;
      var choose_style_index_arr = e.detail.value;
      var choose_style_name = season_show[0][choose_style_index_arr[0]].label + ' - ' + season_show[1][choose_style_index_arr[1]].label  ;
      this.setData({
          [`formData.season_one`]:season_show[0][choose_style_index_arr[0]].label,
          [`formData.season_two`]:season_show[1][choose_style_index_arr[1]].label,
          choose_style_id_arr: [season_show[0][choose_style_index_arr[0]].id, season_show[1][choose_style_index_arr[1]].id],
          choose_style_index_arr: choose_style_index_arr,
          [`sel_text.choose_season_name`]: choose_style_name
      });
  },
    // 风格分类列变化时
    seasonColumnChange: function (e) {
      // console.log(e);
      var season_data = this.data.season_data;
      var season_show = this.data.season_show;
      var sel_season_arr = this.data.sel_season_arr;
      var index = e.detail.value;
      if (e.detail.column == 0) {
          // 一级分类改变时
          console.log('一',season_data[index].children)
          this.data.season_show[1] = season_data[index].children;
          sel_season_arr = [index, 0];
      }
      if (e.detail.column == 1) {
          // 二级分类改变时
          console.log('sel_season_arr',sel_season_arr)
          sel_season_arr[1] = index;
      }
      // 重新渲染
      this.setData({
          season_show: this.data.season_show,
          sel_season_arr: sel_season_arr
      });
  },
    propChange: function (e) {
      this.setData({
        [`formData.first_order`]: this.data.prop_list[e.detail.value].value,
      })
    },
    blChange: function (e) {
      this.setData({
        [`formData.is_bl`]: this.data.is_bl_options[e.detail.value].value,
      })
    },
            // 获取时间分类
            get_season_show: function () {
              // 发起请求
              var res = this.data.season_data
              this.setData({
                season_show: [res, res[0].children],
              });
      },
    onLoad(options) {
      const currentYear = new Date().getFullYear();
    this.setData({
      [`formData.year`]: currentYear.toString()
    });
      this.get_web_config();
      this.get_season_show();
        wx.setNavigationBarTitle({
            title: '新增采购单'
        });
        // 如果是修改
        if (options.purchase_id != undefined) {
            this.setData({
                purchase_id: options.purchase_id
            });
            wx.setNavigationBarTitle({
                title: '修改采购单'
            });
        }
        // 获取数据
        this.get_data_all();
    },

    // 获取采购员
    get_buyer_list: function () {
        // 发起请求
        var result = app.request_api('admin/auth.admin/index', {
            select: true,
            limit: 9999,
            group_id: 7
        }, false);
        result.then(res => {
            console.log(res)
            this.setData({
                buyer_list: res.list
            });
        });
        // 返回
        return result;
    },
    mini_add(){
        wx.navigateTo({
          url: '/pages/purchase_add_pro/purchase_add_pro',
        })
    },
    // 获取供应商
    get_supplier_list: function (is_search = 0) {
        var __this = this;
        // 验证
        if ((this.data.supplier_list.length >= this.data.supplier_total) && this.data.supplier_now_page > 0) {
            return false;
        }
        // 发起请求
        var result = app.request_api('admin/Supply/index', {
            page: __this.data.supplier_now_page + 1,
            quick_search: __this.data.supplier_keywords,
            limit: __this.data.limit,
            select:true,
        }, false);
        result.then(res => {
            console.log(res)
            if (is_search == 1) {
                __this.setData({
                    supplier_list: [],
                    supplier_now_page: 0,
                    supplier_total: 0
                })
            }
            __this.setData({
                supplier_list: __this.data.supplier_list.concat(res.list),
                supplier_now_page: this.data.supplier_now_page + 1,
                supplier_total: res.total
            })
        });
        // 返回
        return result;
    },

    // 输入框改变
    formInputChange(e) {
        const {field} = e.currentTarget.dataset
        this.setData({
            [`formData.${field}`]: e.detail.value.trim()
        });
    },

    // 是否是首单
    firstOrderChange: function (e) {
        var first_order = false;
        if (e.detail.value) {
            first_order = true;
        }
        this.setData({
            [`formData.first_order`]: first_order
        })
    },

    // 采购时间
    bindDateChange: function (e) {
        console.log(e);
        this.setData({
            [`formData.purchase_time`]: e.detail.value
        })
    },

    // 采购员改变时
    buyerChange: function (e) {
        this.setData({
            [`formData.buyer_id`]: this.data.buyer_list[parseInt(e.detail.value)].id,
            [`sel_text.buyer_text`]: this.data.buyer_list[parseInt(e.detail.value)].realname
        })
    },

    // 订单属性改变时
    typeChange: function (e) {
        this.setData({
            [`formData.type`]: this.data.type_list[parseInt(e.detail.value)].id,
            [`sel_text.type_text`]: this.data.type_list[parseInt(e.detail.value)].name
        })
    },

    // 选择供应商
    choose_supplier: function (e) {
        // 清空已选择的物料
        if (this.data.supplier_list[parseInt(e.currentTarget.dataset.index)].id != this.data.formData.supply_id) {
            this.setData({
                bom_list: [],
            })
        }
        // 验证是否选择的是否和之前一样
        this.setData({
            [`formData.supply_id`]: this.data.supplier_list[parseInt(e.currentTarget.dataset.index)].id,
            [`sel_text.supply_text`]: this.data.supplier_list[parseInt(e.currentTarget.dataset.index)].SupplyNa
        });
        this.close_supplier_choose();
    },

    // 打开选择
    open_supplier_choose: function () {
        this.setData({
            is_shade_screen: true,
            is_show_choose_supplier: true
        })
    },

    // 关闭
    close_supplier_choose: function (e) {
        this.setData({
          is_shade_screen: false,
          is_show_choose_supplier: false,
          is_show_choose_pro: false,
        })
    },

    // 搜索供应商时
    searchSupplierChange: function (events) {
        var keywords = events.detail.value.trim();
        this.setData({
            supplier_keywords: keywords,
            supplier_list: [],
            supplier_now_page: 0,
            supplier_total: 0,
        });
        this.get_supplier_list(1);
    },

    // 选择物料
    ChooseWuliao: function (events) {
        var __this = this;
        // 验证是否选择供应商
        if (__this.data.formData.supply_id == 0) {
            wx.showToast({
                title: '请先选择供应商',
                icon: 'none',
                duration: 1500,
            });
            return false;
        }
        // 打开选择颜色页面
        wx.navigateTo({
            url: '/pages/choose_wuliao/choose_wuliao',
            events: {
                // 当选择完成时
                changeData: function (data) {
                    console.log(data);
                    __this.setData({
                        bom_list: data
                    });
                }
            },
            success: function (res) {
                // 向被打开页面传送数据
                res.eventChannel.emit('acceptDataFromOpenerPage', {
                    bom_list: __this.data.bom_list,
                    supply_id: __this.data.formData.supply_id
                });
            }
        });
    },

    
getTotalBom(template_id,index){
  
  let search = []
  search.push({field:"template.template_id",operator:"=",val:template_id})

  var res = app.request_api("/admin/TotalBom/index",{search,select:true});
  res.then((res)=>{
    let new_list = []
    for(var k in res.list){
      new_list.push(res.list[k])
    }
    console.log(new_list, res.list)
    let bom_list = this.data.bom_list;
    bom_list[index].pro_list = new_list
    bom_list[index].pro_list_ = res.list
    this.setData({
      bom_list
    })
  })
  
},

    // 搜索供应商时
    searchBomChange: function (events) {
      var keywords = events.detail.value.trim();
      let  bom_list = this.data.bom_list;
      let bom_index = this.data.bom_index
      bom_list[bom_index].bom_id={bom_option_name:keywords};
      this.setData({
        bom_list,
      });
  },
    // 当输入时
    selFormInputChange: function (e) {
      console.log('修改了',e)
        var index = e.currentTarget.dataset.index;
        var field = e.currentTarget.dataset.field;
        this.data.bom_list[index][field] = e.detail.value.trim();
        this.setData({
            bom_list: this.data.bom_list
        });
        if(field=='template_no'){
          //获取生产批次
            let search=[];
            let bom_list = this.data.bom_list
            bom_list[index].total_bom_id=0;
            bom_list[index].pro_list=[];
            bom_list[index].pro_list_=[];
            bom_list[index].bom_id=[];
            bom_list[index].totalbom_bom_list=[];
            search.push({operator:"=",val:e.detail.value.trim(),field:"template_no"})
            var res = app.request_api("/admin/Template/index",{search});
            res.then((res)=>{
              bom_list[index].fileList = [];
              bom_list[index].is_close_phot = false;
              this.setData({
                bom_list,
                is_close_phot:false,
              })
              console.log(res.list[0])
              if(res.list[0]!==undefined){
                bom_list[index].is_close_phot=true;
                this.setData({
                  bom_list,
                })
                let {template_id} = res.list[0];
                this.getTotalBom(template_id,index);
                console.log('template_images',res.list[0].template_images)
                var template_images = res.list[0].template_images
                if(template_images!==undefined && Array.isArray(template_images) && template_images.length>0){
                    let fileList = [];
                    template_images.forEach((v,k)=>{
                      fileList.push({
                        "url":v,"thumb":v,"fileType":"image","value":v
                      })
                    })
                    bom_list[index].fileList = fileList;

                    bom_list[index].template_pro_cost = res.list[0].real_template_cost;
                    bom_list[index].template_retail_price = res.list[0].sale_price;

                    bom_list[index].is_close_phot=true;
                    this.setData({
                      bom_list,
                    })
                }
              }
            })
        }
    },

    // 选择交期时
    bindDeadLineChange: function (e) {
        console.log(e);
        var index = e.currentTarget.dataset.index;
        var field = e.currentTarget.dataset.field;
        this.data.bom_list[index][field] = e.detail.value;
        this.setData({
            bom_list: this.data.bom_list
        })
    },

    // 取消选择
    chooseDel: function (e) {
        var index = e.currentTarget.dataset.index;
        this.data.bom_list.splice(index, 1);
        // 重置data
        this.setData({
            bom_list: this.data.bom_list
        });
    },
 // 获取上传标识
 get_web_config: function () {
  // 发起请求
  var result = app.request_api('admin/index/index', {}, true, 'GET');
  result.then(res => {
      console.log(res)
      this.setData({
          web_data: res
      });
  });
},
    // 提交
    formSubmit: function (e) {
        if (this.data.purchase_id > 0) {
            return false;
        }
        var __this = this;

        var req_arr = [];
        this.data.bom_list.forEach((element,index) => {
          var fileList = element.fileList
          if(element.fileList!==undefined){
            fileList.forEach(function(v,k){
              if(v.tempFilePath!==undefined){
                console.log('v.tempFilePath',v.tempFilePath)
                var result = app.request_upload('', {
                  cdn_url: __this.data.web_data.siteConfig.apiUrl,
                  token: __this.data.web_data.siteConfig.upload.token,
                  is_old_file:0
                },v.tempFilePath, k, false);
                req_arr.push(result);
                // 处理结果
                result.then(res => {
                  console.log('sc',res)
                    let insert_data={"url":res.file_path,"thumb":res.file_path,"fileType":"image","value":res.file_key}
                    __this.data.bom_list[index].fileList[res.for_i] = insert_data;
                    __this.setData({
                        bom_list: __this.data.bom_list
                    });
                });
              }
              
            })
          }


          var fileList2 = element.fileList2
          if(element.fileList2!==undefined){
            fileList2.forEach(function(v,k){
              if(v.tempFilePath!==undefined){
                console.log('v.tempFilePath',v.tempFilePath)
                var result = app.request_upload('', {
                  cdn_url: __this.data.web_data.siteConfig.apiUrl,
                  token: __this.data.web_data.siteConfig.upload.token,
                  is_old_file:0
                },v.tempFilePath, k, false);
                req_arr.push(result);
                // 处理结果
                result.then(res => {
                  console.log('sc',res)
                    let insert_data={"url":res.file_path,"thumb":res.file_path,"fileType":"image","value":res.file_key}
                    __this.data.bom_list[index].fileList2[res.for_i] = insert_data;
                    __this.setData({
                        bom_list: __this.data.bom_list
                    });
                });
              }
              
            })
          }
          
        });
      
        // 全部上传成功后调用
        Promise.all(req_arr).then(res => {
          var req_param = __this.data.formData;
          req_param.bom_list = __this.data.bom_list;
          var result = app.request_api('admin/purchase/add', req_param, true);
          result.then(res => {
              // 向上一级页面传递参数
              var eventChannel = __this.getOpenerEventChannel();
              // eventChannel.emit('changeData', {});
              // 跳转回前一页
              console.log(res)
              wx.showModal({
                  title: '提示',
                  content: '提交成功',
                  showCancel: false,
                  complete() {
                    wx.navigateTo({
                      url: '/pages/purchase_list/purchase_list',
                    })
                      // wx.navigateBack();
                  }
              });
          });
        })
       
    },

    // 修改时的提交
    formSubmitUpdate: function (e) {
        if (this.data.purchase_id == 0) {
            return false;
        }
        // 组装参数
        var __this = this;
        var req_param = __this.data.formData;
        req_param.bom_list = __this.data.bom_list;
        req_param.purchase_id = __this.data.purchase_id;
        // 发起请求
        var result = app.request_api('admin/purchase/edit', req_param, true);
        result.then(res => {
            // 向上一级页面传递参数
            var eventChannel = __this.getOpenerEventChannel();
            // eventChannel.emit('changeData', {

            // });
            // 跳转回前一页
            wx.showModal({
                title: '提示',
                content: '保存成功',
                showCancel: false,
                complete() {
                    wx.navigateBack();
                }
            });
        });
    },

    // 请求数据
    get_data_all: function () {
        var __this = this;
        var req_arr = [];
        // 组装请求
        if (this.data.purchase_id > 0) {
            // 获取详情
            var detail_res = this.get_row_data();
            req_arr.push(detail_res);
        }
        // 获取采购员
        var buyer_res = this.get_buyer_list();
        req_arr.push(buyer_res);
        // 获取供应商
        var supplier_res = this.get_supplier_list();
        req_arr.push(supplier_res);
        // 全部完成
        Promise.all(req_arr).then(res => {
            console.log(res);
            if (__this.data.purchase_id > 0) {
                // 采购员
                var buyer_text = '';
                var buyer_index = __this.data.buyer_list.findIndex(obj => obj.id === __this.data.formData.buyer_id);
                if (buyer_index > -1) {
                    buyer_text = __this.data.buyer_list[buyer_index].realname;
                }
                __this.setData({
                    [`sel_text.buyer_text`]: buyer_text,
                });
                // 重新请求供应商
                if (__this.data.formData.supply_id > 0) {
                    __this.setData({
                        supplier_list: [],
                        supplier_total: 0,
                        supplier_now_page: 0,
                        supplier_keywords: __this.data.formData.supply_id
                    });
                    var supplier_res2 = this.get_supplier_list();
                    supplier_res2.then(res2 => {
                        console.log(res2)
                        if (res2.list.length > 0) {
                            var supplier_index = res2.list.findIndex(obj => obj.id === __this.data.formData.supply_id);
                            if (supplier_index > -1) {
                                __this.setData({
                                    [`sel_text.supply_text`]: res2.list[supplier_index].SupplyNa,
                                });
                            }
                        }
                    });
                }
            }
        }).catch(error => {
            console.log(error);
        });
    },
    setSeasonName({season_one,season_two}){
      let {season_data} = this.data
      let index1 = season_data.findIndex(res=>res.label===season_one)
      if(index1!==-1){
        let index2 = season_data[index1].children.findIndex(res=>res.label===season_two)
        if(index2!==-1){
          let choose_style_name = season_data[index1].label+" - "+season_data[index1].children[index2].label
          this.setData({
            // choose_style_id_arr: [season_show[0][choose_style_index_arr[0]].id, season_show[1][choose_style_index_arr[1]].id],
            choose_style_index_arr: [index1,index2],
            [`sel_text.choose_season_name`]: choose_style_name
          });
          console.log('index1index1index1',index1,index2)
        }
      
      }
      
    },
    // 获取详情
    get_row_data: function () {
        var result = app.request_api('admin/Purchase/edit', {
            purchase_id: this.data.purchase_id
        }, true, 'GET');
        result.then(res => {
            console.log(res);
            var type_index = this.data.type_list.findIndex(obj => obj.id === res.row.type);
            var type_text = '';
            if (type_index > -1) {
                type_text = this.data.type_list[type_index].name
            }
            this.setSeasonName(res.row);
            this.setData({
                edit_data: res.row,
                [`formData.purchase_time`]: res.row.purchase_time,
                [`formData.purchase_name`]: res.row.purchase_name,
                [`formData.first_order`]: res.row.first_order,
                [`formData.buyer_id`]: res.row.buyer_id,
                [`formData.type`]: res.row.type,
                [`formData.season_one`]: res.row.season_one,
                [`formData.season_two`]: res.row.season_two,
                [`formData.year`]: res.row.year,
                [`formData.supply_id`]: res.row.supply_id,
                [`formData.sg_purchase_sn`]: res.row.purchase_sn,
                [`formData.is_bl`]: res.row.is_bl,
                [`sel_text.type_text`]: type_text,
                
                bom_list: res.row.bom_list
            });
        });
        // 返回
        return result;
    },


})